package com.atguigu.netty.group.chat.server;

import com.alibaba.fastjson.JSON;
import com.atguigu.netty.group.chat.Message;
import com.atguigu.netty.group.chat.model.MsgDTO;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GroupChatServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * channel管理组
     */
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * @Description: 读取消息
     * @param ctx:  下上文对象，含有管道，通道，地址
     * @param msg: 客户端发送的对象
     * @return void
     * @since 2021/3/14 16:05
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 客户端发送的消息
        ByteBuf byteBuf = (ByteBuf) msg;
        String clientMsg = byteBuf.toString(CharsetUtil.UTF_8);
        MsgDTO msgDTO = JSON.parseObject(clientMsg, MsgDTO.class);
        Channel currChannel = ctx.channel();
        if (!channelGroup.contains(currChannel)) {
            channelGroup.add(currChannel);
            log.info("用户{}上线",msgDTO.getUserName());
        }
        // 格式化消息
        String buildMsg = Message.buildMsg(msgDTO);
        System.out.println(buildMsg);
        for (Channel channel : channelGroup) {
            channel.writeAndFlush(Unpooled.copiedBuffer(buildMsg,CharsetUtil.UTF_8));
        }
    }

    /**
     * @Description: 数据读取完毕
     * @param ctx:
     * @return void
     * @since 2021/3/14 16:08
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }

    /**
     * @Description:  异常处理
     * @param ctx:
     * @param cause:
     * @return void
     * @since 2021/3/14 16:09
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
